import axios from "axios";
import { getToken } from "@/utils/auth";
import { fileDelete } from "@/api/common/file";

export const uploadUrl = "/file/upload";
// export const uploadUrl = "/api/file/upload";

export function debounce(fn, delay) {
  // 记录上一次的延时器
  var timer = null;
  var delay = delay || 300;
  return function () {
    var args = arguments;
    var that = this;
    // 清除上一次延时器
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay);
  }
}


export function createFormData(form) {
  let formData = new FormData();
  for (const key in form) {
    const element = form[key];
    formData.append(key, element || null);
  }
  return formData;
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function autoTableHeight(height = 260, callback) {
  let tableHeight = document.documentElement.clientHeight - height;
  callback(tableHeight)
  window.onresize = function () {
    let tableHeight = document.documentElement.clientHeight - height;
    callback(tableHeight)
  };
}

export function findTreeParent(tree, target, parentStore) {
  for (let i in tree) {
    let item = tree[i]
    if (item.id === target) {
      let { name, id } = item;
      parentStore.unshift({
        name,
        id,
      })
      return true
    }
    if (item.children && item.children.length > 0) {
      let ok = findTreeParent(item.children, target, parentStore)
      if (ok) {
        let { name, id, price } = item;
        parentStore.unshift({
          name,
          id,
          price
        })
        return true
      }
    }
  }
  return false
}


export async function fileRemove(that, url, belongTo, callback) {
  return new Promise((resolve, reject) => {
    that.$confirm(`将删除该资源, 是否继续?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        fileDelete({
          url,
          belongTo
        }).then((res) => {
          callback()
        });
      })
      .catch(() => {
        thithats.$message({
          type: "info",
          message: "已取消删除",
        });
        reject(false)
      });
  })
}

export function beforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 0.01;
  if (!isLt2M) {
    this.$message.error('上传头像图片大小不能超过 2MB!');
  }
  debugger;
  return isLt2M
}


export async function fileUpload(that, fileObject, belongTo) {
  let fileType = fileObject.file.type;
  if (fileType.indexOf('image') != -1 && fileObject.file.size > 1024 * 500) {
    that.$message({
      message: "上传图片大小不能超过 2000kb!",
      type: "error",
    });
    return;
  }
  let fd = new FormData();
  fd.append("belongTo", belongTo);
  fd.append("file", fileObject.file);
  let config = {
    headers: {
      from: "web",
      Authorization: getToken(),
      'Content-Type': 'multipart/form-data'
    },
  };
  const loading = that.$loading({
    lock: true,
    text: '上传中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.3)',
  });
  const { data: res } = await axios.post(uploadUrl, fd, config);
  setTimeout(() => {
    loading.close();
  }, 500);
  if (res.code !== 10001) return;
  return res.data;
}